<!--
 * @description  : 公共文书
 * @descriptionDetail: 公共文书
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-08-24 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->
    <view class="content u-page">
      <u-cell-group>
        <u-cell-item
          :arrow="false"
          :iconStyle="iconCustomStyle"
          :customPrefix="getCustomPrex(pi.icon)"
          :icon="getIconName(pi.icon)"
          :title="pi.title"
          :iconSize="42"
          :value-style="valueStyle"
          v-for="pi in commonDoc.pageInfos"
          :key="pi.title"
        >
          <view class="lay-file-root">
            <view class="lay-file" style="text-align: right;">
              {{ docData[pi.column] }}
            </view>
          </view>
        </u-cell-item>
        <u-cell-item
          :arrow="false"
          :iconStyle="iconCustomStyle"
          customPrefix="csbi-icon"
          icon="crosshairmiaozhun"
          title="当前环节"
          :iconSize="42"
          :value-style="valueStyle"
        >
          {{ docIns.stepName }}
        </u-cell-item>
        <u-cell-item
          :arrow="false"
          :iconStyle="iconCustomStyle"
          customPrefix="csbi-icon"
          icon="guangqi_bangzhuwendang"
          title="文书"
          :iconSize="42"
          :value-style="valueStyle"
          v-if="showPdf"
        >
          <view class="lay-file-root">
            <view class="lay-file" v-if="docIns.pdfFileId" @click="downloadFile()">
              <u-image src="/static/pdf.png" width="50rpx" height="50rpx"></u-image>
              <text class="lay-file-title">
                {{ commonDoc.name }}
              </text>
            </view>
            <view class="lay-file" v-else>
              未生成文书
            </view>
          </view>
        </u-cell-item>
        <u-cell-item
          :arrow="false"
          :iconStyle="iconCustomStyle"
          icon="file-text-fill"
          title="备注"
          :iconSize="42"
          :value-style="valueStyle"
          v-if="!!docData.memo"
        >
          {{ docData.memo }}
        </u-cell-item>
        <u-cell-item
          :iconStyle="iconCustomStyle"
          customPrefix="csbi-icon"
          icon="crosshairmiaozhun"
          title="审核审批时间"
          :iconSize="42"
          :value-style="valueStyle"
          @click="onDatePick"
        >
          {{ initAppDate }}
        </u-cell-item>
        <u-cell-item
          :iconStyle="iconCustomStyle"
          customPrefix="csbi-icon"
          icon="liucheng"
          title="办理流程"
          :iconSize="42"
          :value-style="valueStyle"
          :arrow-direction="liuchengShow?'down':'right'"
          @click="liuchengShow = !liuchengShow"
        >
        </u-cell-item>
        <u-cell-item :arrow="false" title="" v-show="liuchengShow">
          <view style="width: 100%;padding-left: 50rpx;color: #000000;">
            <view class="timeline-item">
              <view class="timeline-item-date"></view>
              <view class="timeline-item-divider"></view>
              <view class="timeline-item-content">
                <view class="timeline-item-title">
                  开始
                </view>
              </view>
            </view>
            <view class="timeline-item" v-for="(his, index) in flowHis" :key="index">
              <view class="timeline-item-date">
                {{ his.opTime }}
              </view>
              <view class="timeline-item-divider timeline-finish" v-if="his.opType == 1"></view>
              <view class="timeline-item-divider timeline-todo" v-if="his.opType != 1"></view>
              <view class="timeline-item-content">
                <view class="timeline-item-title">
                  {{ his.approvePersonName }}
                </view>
                <view class="timeline-item-text">
                  {{ his.gfaName }}
                </view>
              </view>
            </view>
          </view>
        </u-cell-item>
      </u-cell-group>
    </view>
    <view class="btm-lay" v-if="docIns.step != 'view'">
      <u-button size="default" plain type="error" @click="returnAudit">
        退回
      </u-button>
      <u-button size="default" plain type="primary" @click="submitAudit">
        通过
      </u-button>
    </view>
    <u-calendar mode="date" v-model="calShow" @change="dateConfirm"></u-calendar>
    <u-modal title="审批意见" :title-style="titleStyle" :confirm-style="confirmStyle" v-model="promptShow" @confirm="prompConfirm">
      <view class="slot-content">
        <u-input placeholder="请输入审批意见" type="text" :border="false" v-model="prompText"></u-input>
      </view>
    </u-modal>
  </view>
</template>

<script>
import {
  COMMON_DOC,
} from "@/service/enum/common-doc";
import commonService from "@/service/common/common.service";
import officeService from "@/service/case/office.service";
import certService from "@/service/certificate/certificate.service";
import {LOG_STATUS,LOG_OP_TYPE,} from '@/service/common/mapping/enum.js';
export default {
  onLoad() {
    this.showDefaultTitle = false;
  },
  data() {
    return {
      titleStyle:{
        color:'#000000',
        fontWeight:'bold',
        fontSize:'18px',
      },
      confirmStyle:{
        color:'#fff',
        background:'#0487FB',
        borderRadius:'12px',
        fontSize:'14px',
        height:'40px',
        lineHeight:'40px',
        margin:'20px',
      },
      user: undefined,
      calShow: false,
      promptShow: false,
      prompText: "同意",
      liuchengShow: false,
      iconCustomStyle: {
        color: this.$theme.u_type_primary,
      },
      valueStyle: {
        color: "#000000",
      },
      gfaCode: "",
      commonDoc: {},
      docIns: {},
      flowHis: [],
      approves: [],
      docData: {},
      initAppDate: this.$u.date(Date.now(), 'yyyy-mm-dd'),
      tmpParam: undefined,
      showPdf:true,
      beginTime:"",
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let self = this;
      commonService.getCurrentTime().then(res2 => {
        this.beginTime = res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss');
      });
      commonService.getCurrUserInfo().then(userInfo => {
        self.user = userInfo;
      });
      this.initDocData();
    },
    onDatePick() {
      this.calShow = true;
    },
    dateConfirm(e) {
      this.initAppDate = e.result;
    },
    prompConfirm() {
      let da = {};
      da.isAgree = 1;
      da.approveInfo = this.prompText;
      this.beforeAgreeSubmit(da);
    },
    updateBackState(param) {
      console.log('updataBackState的param' + param );
      if (param.backApprove) { // 退回操作 回调
        let da = {};
        da.docInsUuid = this.docIns.docInsUuid;
        da.gfaCode = this.docIns.step;
        da.isAgree = "0";
        da.approvePersonUuid = this.user.user.personUuid;
        da.opType = param.backApprove.backFlag;
        da.approveInfo = param.backApprove.remark;
        if (!da.approveInfo) {
          this.$modal.alert("请填写退回意见");
          return;
        }
        // 执行退回操作
        this.doReturn(da);
      } else if (param.auditApprove) { // 审批意见页面返回
        let pa = {};
        pa.approveInfo = param.auditApprove.remark;
        pa.isAgree = param.auditApprove.isAgree;
        this.beforeAgreeSubmit(pa);
      } else if (param.flowUserSelectBack) { // 选择审批人
        let nextPersons = [];
        for (let fu of param.flowUserSelectBack) {
          nextPersons.push(fu.personId);
        }
        this.doSubmit(this.tmpParam, nextPersons.join(","));
      }
    },
    returnAudit() {
      this.$u.route("/pages/todo/components/backApproveComponent");
    },
    /**
	 * 退回操作
	 */
    doReturn(da) {
      this.$modal.showLoading('退回中...');
      let returnPromise = this.calcPromise("back", {
        da: da,
      });
      let self = this;
      returnPromise.then((rs) => {
        self.$modal.hideLoading();
        if(rs.success){
          this.saveBehaviorLog(LOG_OP_TYPE.agree, this.docIns);
          self.backPrev({
            paramKey: "refresh",
            param: true,
          });
        }else{
          self.$modal.alert(rs.msg);
        }
      }, (err) => {
        self.$modal.hideLoading();
        self.$modal.alert(err.msg);
      });
    },
    submitAudit() {
      let da = {};
      let currStep = this.docIns.step;
      // 审核审批通过扩展页面补充信息
      if (this.commonDoc['agreeExtend'] && this.commonDoc['agreeExtend'][currStep]) {
        let obj = {
          currStep: currStep,
          gfcode: this.commonDoc['gfCode'],
          parent: this.commonDoc['parent'],
          docData: this.docData,
          comments: this.commonDoc.comments ? this.$u.deepClone(this.commonDoc.comments[currStep]) : undefined,
        };
        if(this.commonDoc['parent'] == 'lic' && (this.commonDoc['gfCode'] == 'docAuthApproveNew' || this.commonDoc['gfCode'] == 'docAuthApprove')){
          if(obj.comments && this.docData.applyTypeName){
            obj.comments.forEach(itm => {
              itm.name += this.docData.applyTypeName;
            });
          }
        }
        this.setRouteParam(obj);
        this.$u.route("/pages/todo/components/agreeApproveComponent");
        return;
      }
      this.promptShow = true;
    },
    /**
			 * 审核审批通过之前的数据组装
			 */
    beforeAgreeSubmit(da) {
      da.opType = 1;
      da.docInsUuid = this.docIns.docInsUuid;
      da.docUuid = this.docIns.docUuid;
      da.gfaCode = this.docIns.step;
      da.titemUuid = this.docIns.configIns.titemUuid;
      da.approvePersonUuid = this.user.user.personUuid;
      if (!da.approveInfo) {
        this.$modal.alert("请填写" + (this.docIns.step === 'audit' ? "审核" : "审批") + "意见");
        return;
      }
      // 审核时选择审批节点人员
      if (this.approves.length == 0) {
        this.$modal.alert("当前待办没有流程");
        return;
      }
      // 如果当前不是结束节点则选择审核审批人员
      if (this.docIns.step !== this.approves[this.approves.length - 1].gfaCode) {
        this.tmpParam = da;
        this.$u.route({
          url: "/pages/commonPage/flowUserSelectComponent",
          params: {
            flowFormCode: this.docIns.configIns.flowFormCode,
            docInsUuid: this.docIns.docInsUuid,
          },
        });
      } else {
        // 案件处理审批表增加提示
        if (this.gfaCode === "docCaseHandle") {
          this.$modal.alert("请确认当事人姓名(名称)、身份证件信息是否正确，此数据一经提交将推送国家互联网+监管系统！", "提示", () => {
            this.doSubmit(da);
          });
        } else {
          this.doSubmit(da);
        }
      }
    },
    /**
	 * 执行提交操作
	 */
    doSubmit(da, nextPersons) {
      this.$modal.showLoading(this.docIns.step === "01" ? "审核中..." : "审批中...");
      let submitPromise = this.calcPromise("submit", {
        da: da,
        nextPersons: nextPersons,
      });
      submitPromise.then((rs) => {
        this.$modal.hideLoading();
        if (rs.success) {
          this.saveBehaviorLog(LOG_OP_TYPE.agree, this.docIns);
          this.backPrev({
            paramKey: "refresh",
            param: true,
          });
        } else {
          this.$modal.alert(rs.msg);
        }
      }, (err) => {
        this.$modal.hideLoading();
        // this.alert(err.msg);
      });
    },
    /**
	 * 初始化文书信息
	 */
    initDocData() {
      console.log('进入文书');
      this.$modal.showLoading("文书加载中...");
      let params = this.getRouteParam();
      let self = this;
      this.gfaCode = params["gfCode"];
      if(this.gfaCode == 'dirReplenish'){  // 是拆卷申请则不展示文书选项
        this.showPdf = false;
      }
      this.commonDoc = COMMON_DOC[this.gfaCode];
      this.navTitle = this.commonDoc.name;
      // 文书实例信息
      officeService.getDocIns(params['docInsUuid']).then((res) => {
        console.log('文书实例成功')
        this.updateTitle();
        if (res.success) {
          self.docIns = res.bean;
          // 文书信息1
          self.initDoc();
          officeService.approves({
            id: self.docIns.docInsUuid,
            docUuid: self.docIns.docUuid,
          }).then((approves) => {
            self.approves = approves.data;
          });
          // 审批历史
          officeService.flowHis({
            gfCode: self.docIns.configIns.docCode,
            docInsUuid: self.docIns.docInsUuid,
          }).then((flows) => {
            self.flowHis = flows.data.reverse();
          }, (err) => {
            console.log("查询审批历史出错", err);
          });
        } else {
          this.$modal.hideLoading();
          this.$modal.alert("查询出错:" + res.msg);
        }
      }).catch(err => {
        console.log('查询报错')
        this.$modal.hideLoading();
        this.updateTitle();
        this.$modal.alert("查询出错:" + err);
      });
    },
    updateTitle(){
      this.$deviceApi.setTitle && this.$deviceApi.setTitle(COMMON_DOC[this.gfaCode].name);
      this.navTitle = COMMON_DOC[this.gfaCode].name;
      this.$forceUpdate();
    },
    /**
			 * 设置默认意见
			 */
    initDoc() {
      let self = this;
      let docParam = {
        id: this.docIns.docInsUuid,
        docUuid: this.docIns.docUuid,
        bizUuid: this.docIns.bizUuid,
      };
      let initPromise = this.calcPromise("init", docParam);
      if (!initPromise) {
        self.$modal.hideLoading();
        this.$modal.alert("未生成PDF文书");
        return;
      }
      // 申请单信息(例如依申请办理审批表中企业名称无法通过文书获取，只能查询申请表的原始数据)
      let applyDataPromise = officeService.getApplyByMainId(this.docIns.bizUuid);
      Promise.all([initPromise, applyDataPromise,]).then((ds) => {
        self.$modal.hideLoading();
        self.docData = ds[0].data[0];
        let applyData = ds[1].bean || {};
        for (let pi of self.commonDoc.pageInfos) {
          // 文书信息中内容为空且申请表单信息中存在，将此页面显示值加入到文书信息中
          !self.docData[pi.column] && !!applyData[pi.column] && (self.docData[pi.column] = applyData[
            pi.column]);
        }
      }, (err) => {
        self.$modal.hideLoading();
        self.$modal.alert(err.msg);
      });
    },
    calcPromise(type, param) {
      // 审核审批时间
      if (type != 'init')
        param.da.approveDate = this.$u.timeFormat((new Date(this.initAppDate)).getTime(), 'yyyy年mm月dd日');
      if (this.commonDoc.parent == "lic") {
        return this.calcLicPromise(type, param);
      } else {
        return this.calcCasePromise(type, param);
      }
    },
    /**
			 * 获取证件文书信息初始化、提交、退回接口的Promise
			 */
    calcLicPromise(type, param) {
      let funType = this.commonDoc.functions[type];
      let promise = null;
      switch (type) {
      case "init": // 初始化
        promise = certService[funType](param, this.commonDoc.controllerPath);
        break;
      case "submit": // 提交
        promise = certService[funType](this.docData, param.da, param.nextPersons, this.commonDoc.controllerPath);
        break;
      case "back": // 退回上一步
        promise = certService[funType](this.docData, param.da, this.commonDoc.controllerPath);
        break;
      case "backEdit": // 退回修改
        // promise = certService[funType](this.docData, _param.da);
        break;
      default:
        break;
      }
      return promise;
    },
    /**
			 * 获取案件文书信息初始化、提交、退回接口的Promise
			 */
    calcCasePromise(type, param) {
      let funType = this.commonDoc.functions[type];
      let promise = null;
      switch (type) {
      case "init": // 初始化
        promise = officeService[funType](param, this.commonDoc.controllerPath);
        break;
      case "submit": // 提交
        promise = officeService[funType](this.docData, param.da, param.nextPersons, this.commonDoc.controllerPath);
        break;
      case "back": // 退回上一步
        promise = officeService[funType](this.docData, param.da, this.commonDoc.controllerPath);
        break;
      case "backEdit": // 退回修改
        // promise = officeService[funType](this.docData, param.da);
        break;
      default:
        break;
      }
      return promise;
    },
    getCustomPrex(type) {
      if (type == 1) {
        return "csbi-icon";
      } else if (type == 2) {
        return "uicon";
      } else if (type == 3) {
        return "uicon";
      } else if (type == 4) {
        return "uicon";
      }else{
        return "";
      }
    },
    getIconName(type) {
      if (type == 1) {
        return "daochu";
      } else if (type == 2) {
        return "account";
      } else if (type == 3) {
        return "calendar";
      } else if (type == 4) {
        return "chat";
      }else {
        return "";
      }
    },
    downloadFile(){
      // 定义跳转参数
      const params = {
        fileId: this.docIns.pdfFileId,
        fileName: this.commonDoc.name,
      };
      this.setRouteParam(params);
      // 跳转详情页面
      this.$u.route("/pages/commonPage/printerComponent");
    },
    /**
	 * @param {Boolean} status 提交还是保
	 */
    saveBehaviorLog(status, doc){
      commonService.getCurrentTime().then(res2 => {
        let param = {
          bizUuid: doc.bizUuid,
          docUuid:doc.docUuid,
          docInsUuid: doc.docInsUuid, 
          bizType:LOG_STATUS.B007,
          operationType: status,
          beginTime: this.beginTime,
          endTime: res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'),
          remark: doc.configIns.docName,
        };
        this.beginTime = param.endTime;
        commonService.saveBehaviorLog(param).then(res => {
          console.log(res);
        }).catch(e => {
          console.log(e);
        });
      });
    },
  },
}
</script>

<style scoped lang="scss">
	.content {
		padding-bottom: 50px;
	}

	.item-inner .item-title.label {
		width: 35%;
	}

	.display-flex {
		display: flex !important;
		justify-content: center;
		align-items: center;
	}

	.input-label {
		min-width: 80px;
		display: flex;
		justify-content: center;
		align-items: center;

		input[type='radio'],
		input[type='checkbox'] {
			width: 14px;
		}
	}

	.article-title {
		text-align: center;
		background-color: #FFF;
	}

	.article-main-title {
		color: #000000;
		font-size: 18px;
		text-align: center;
		color: #000;
		font-weight: 600;
	}

	.article-sub-title {
		font-size: 15px;
		margin: 3px;
	}

	.article-content-detail {
		margin: 3px;
		text-align: center;
		color: #000;
		height: 22px;
		font-size: 13px;
	}

	.basic-info:after {
		display: none;
	}

	.auditList:before {
		display: none;
	}

	.basic-info li:last-child .item-inner {
		border-bottom: 0.5px solid #E6E6E8;
	}

	.long-txt {
		width: 65%;
		white-space: normal;
		max-height: 150px;
		overflow-y: auto;
	}

	.list textarea {
		height: 60px;
		font-size: 13px;
		border: 1px groove;
		padding: 5px;
	}

	.list textarea:disabled {
		border: none;
	}

	.item-content-detail img {
		height: 12px;
	}

	.returnAudit {
		color: #000 !important;
	}

	.part-title {
		text-align: center;
		font-weight: 600;
		padding: 6px;
		background-color: #fff;
		font-size: 14px;
	}

	.text-label {
		color: #000;
		text-align: left;
	}

	.btm-lay {
		display: flex;
		flex-direction: row;
		position: fixed;
		bottom: 0;
		width: 100%;
		padding: 20rpx 0;
	}

	.lay-root {
		width: 100%;
		padding: 40rpx 30rpx;
		display: inline-flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.lay-title {
		align-self: center;
		flex-shrink: 0;
		font-size: 32rpx;
	}

	.block {
		padding: 10px 0px;
	}

	.lay-content {
		align-self: center;
		word-wrap: break-word;
		word-break: break-all;
		font-size: 28rpx;
		white-space: normal;
		overflow: hidden;
	}

	.lay-file-root {
		display: flex;
		flex-direction: column;
	}

	.lay-file {
		align-self: flex-end;
		margin: 10rpx;
		padding-left: 50rpx;
		display: inline-flex;
		flex-direction: row;
		align-items: center;
	}

	.timeline-item {
		padding: 2px 0px 15px;
		display: flex;
		justify-content: flex-start;
		overflow: hidden;
		box-sizing: border-box;
		position: relative;
	}

	.lay-file-title {
		font-size: 30rpx;
		margin-left: 15rpx;
		color: $u-type-primary;
	}

	.timeline-todo {
		background-color: red !important;
	}

	.timeline-finish {
		background-color: green !important;
	}

	.timeline-item-date {
		width: 100px;
		flex-shrink: 0;
		text-align: right;
		box-sizing: border-box;
	}

	.timeline-item-divider {
		margin-left: 15px;
		margin-right: 15px;
		position: relative;
		width: 10px;
		height: 10px;
		background: #bbb;
		border-radius: 50%;
		margin-top: 3px;
		flex-shrink: 0;
	}

	.timeline-item-divider:after {
		top: 100%;
	}

	.timeline-item-divider:before {
		bottom: 100%;
	}

	.timeline-item-divider:after,
	.timeline-item-divider:before {
		background-color: #c7c2c2;
		content: ' ';
		width: 1px;
		height: 100vh;
		position: absolute;
		left: 50%;
		transform: translate3d(-50%, 0, 0);
	}

	.timeline-item:last-child .timeline-item-divider:after {
		display: none;
	}

	.timeline-item:first-child .timeline-item-divider:before {
		display: none;
	}

	.timeline-item-content {
		margin: 2px;
		min-width: 0;
		position: relative;
		flex-shrink: 10;
		text-align: left;
	}

	.timeline-item-title {
		font-size: 17px;
		font-weight: 600;
	}

	.slot-content {
		padding: 30rpx;
	}

	/deep/uni-button {
		width: 40%;
	}
</style>
